<template>
  <Dialog v-model="dialogVisible" title="查看打卡活动" width="1000px">
    <div v-if="formData">
      <el-form :model="formData" label-width="120px" class="demo-form-inline">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活动编号:">
              <span>{{ formData.id }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动名称:">
              <span>{{ formData.name }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间:">
              <span>{{ formatTimestamp(formData.startTime) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间:">
              <span>{{ formatTimestamp(formData.endTime) }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="打卡规则:">
              <span>{{ getPunchCardRuleText(formData.punchCardRule) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="打卡天数:" v-if="formData.punchCardDays">
              <span>{{ formData.punchCardDays }}天</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活动前后凭证:">
              <span>{{ formData.activityUploadProof ? '需要' : '不需要' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="凭证审核:">
              <span>{{ formData.proofCheck ? '需要' : '不需要' }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活动状态:">
              <el-tag :type="formData.status === 0 ? 'success' : 'danger'">
                {{ formData.status === 0 ? '开启' : '关闭' }}
              </el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间:">
              <span>{{ formatTimestamp(formData.createTime) }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="每日打卡时间:" v-if="formData.everydayPunchPeriods">
          <div>
            <el-tag
              v-for="(period, index) in getPunchPeriods(formData.everydayPunchPeriods)"
              :key="index"
              class="mr-2 mb-2"
            >
              {{ period.start }} - {{ period.end }}
            </el-tag>
          </div>
        </el-form-item>

        <el-form-item label="通知文案:" v-if="formData.notifyCopy">
          <div class="text-content">{{ formData.notifyCopy }}</div>
        </el-form-item>

        <el-form-item label="活动规则:" v-if="formData.activityRule">
          <div class="text-content">{{ formData.activityRule }}</div>
        </el-form-item>

        <el-form-item label="关联商品:" v-if="productDetails.length > 0">
          <div class="selected-products">
            <div class="selected-products-header">
              <span>关联商品 ({{ productDetails.length }})</span>
            </div>
            <el-table :data="productDetails" stripe>
              <el-table-column label="商品编号" prop="id" width="100" />
              <el-table-column label="商品图" width="100">
                <template #default="scope">
                  <el-image
                    :src="scope.row.picUrl || ''"
                    style="width: 60px; height: 60px"
                    :preview-src-list="scope.row.picUrl ? [scope.row.picUrl] : []"
                    preview-teleported
                    fit="cover"
                  />
                </template>
              </el-table-column>
              <el-table-column label="商品名称" prop="name" min-width="200" />
              <el-table-column label="商品分类" prop="categoryName" width="120">
                <template #default="scope">
                  <span>{{ scope.row.categoryName || '未分类' }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <el-button @click="dialogVisible = false">关闭</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { formatDate } from '@/utils/formatTime'
import type { RefundActivityRespVO } from '@/api/mall/promotion/refund/refundActivity'
import * as RefundActivityApi from '@/api/mall/promotion/refund/refundActivity'
import * as LocalLifeSpuApi from '@/api/localLife/spu'
import * as LocalLifeCategoryApi from '@/api/localLife/category'

defineOptions({ name: 'RefundActivityDetail' })

const message = useMessage() // 消息弹窗
const dialogVisible = ref(false)
const formData = ref<RefundActivityRespVO>()
const productDetails = ref<LocalLifeSpuApi.Spu[]>([])

/** 打开弹窗 */
const open = async (id: number) => {
  dialogVisible.value = true
  formData.value = undefined
  productDetails.value = []

  try {
    // 通过API获取退款活动详情
    const data = await RefundActivityApi.getRefundActivity(id)
    formData.value = data

    // 根据products中的spuId查询商品详情
    if (data.products && data.products.length > 0) {
      try {
        const spuIds = data.products.map(p => p.spuId)
        const productList = await LocalLifeSpuApi.getSpuDetailList(spuIds)

        if (productList && productList.length > 0) {
          // 获取所有商品的分类ID
          const categoryIds = [...new Set(productList.map(p => p.categoryId).filter(id => id))]

          // 批量获取分类信息
          const categoryMap = new Map()
          if (categoryIds.length > 0) {
            try {
              // 获取分类列表
              const categoryList = await LocalLifeCategoryApi.getCategoryList({})
              if (categoryList && categoryList.length > 0) {
                categoryList.forEach(category => {
                  categoryMap.set(category.id, category.name)
                })
              }
            } catch (error) {
              console.error('查询分类信息失败:', error)
            }
          }

          // 为商品添加分类名称
          productDetails.value = productList.map(product => ({
            ...product,
            categoryName: categoryMap.get(product.categoryId) || '未分类'
          }))
        } else {
          productDetails.value = []
        }
      } catch (error) {
        console.error('查询商品详情失败:', error)
        productDetails.value = []
      }
    } else {
      productDetails.value = []
    }
  } catch (error) {
    console.error('查询退款活动详情失败:', error)
    message.error('获取活动详情失败')
    dialogVisible.value = false
  }
}

/** 获取打卡规则文本 */
const getPunchCardRuleText = (rule: number) => {
  switch (rule) {
    case 1:
      return '持续打卡'
    case 2:
      return '非持续打卡'
    case 3:
      return '无需打卡'
    default:
      return '未知'
  }
}

/** 解析打卡时间段 */
const getPunchPeriods = (periodsStr: string) => {
  try {
    return JSON.parse(periodsStr)
  } catch {
    return []
  }
}

/** 格式化时间戳为可读的日期时间格式 */
const formatTimestamp = (timestamp: number | string) => {
  if (!timestamp) return ''
  if (typeof timestamp === 'number') {
    return formatDate(new Date(timestamp))
  }
  return formatDate(new Date(parseInt(timestamp)))
}

/** 导出方法 */
defineExpose({
  open
})
</script>

<style scoped>
.demo-form-inline {
  max-width: 100%;
}

.text-content {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 12px;
  line-height: 1.6;
  color: #606266;
  white-space: pre-wrap;
  word-break: break-all;
}

.selected-products {
  width: 100%;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 15px;
  background-color: #fafafa;
}

.selected-products-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-weight: 500;
  color: #303133;
}

.price-text {
  color: #f56c6c;
  font-weight: 500;
}

.low-stock {
  color: #f56c6c;
  font-weight: 500;
}
</style>
